#include "ApplicationWindow.h"
#include "Madlglogon.h"
#include "dlgabout.h"
#include "dlgstandards.h"
#include "dbdata.h"\
//#include <qwt_scale_widget.h>
//#include <qwt_scale_draw.h>
#include <qwt_plot_zoomer.h>
//#include <qwt_plot_panner.h>
//#include <qwt_plot_layout.h>
#include <QFileDialog>
#include "dlgcard.h"
#include "dlgtp.h"

#include "mytp.h"
#include "dlgmethod.h"
#include "dlgtableedit.h"
#include "mcsytimer.h"
#include "mcsythread.h"
#include "DlgOpenSample.h"
#include "printview.h"
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <qwt_legend.h>//QwtLegend
#include "editablesqlmodel.h"
extern CDBdata *pgdb;
extern MUser * puser1;
extern MyTp * ptp;
extern MCsyThread * pcsy;
void ApplicationWindow::on_actionEditSql_triggered()
{
        EditableSqlModel* editableModel=new EditableSqlModel(this);
        editableModel->setQuery("select * from sample where sampleid in tmpid");
//        editableModel->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
//        editableModel.setHeaderData(1, Qt::Horizontal, QObject::tr("First name"));
//        editableModel.setHeaderData(2, Qt::Horizontal, QObject::tr("Last name"));
        QTableView *view = new QTableView;
        view->setModel(editableModel);
        static int offset = 0;

        view->setWindowTitle("EditSql");
        view->move(100 + offset, 100 + offset);
        offset += 20;
        view->show();
}
ApplicationWindow::ApplicationWindow(QWidget *parent)
    : QMainWindow(parent)
{
    d_zoomer=0;
    d_python_config_folder="";
    ui.setupUi(this);
    model = new QSqlQueryModel(this);
    // model->setTable("sample");
    model->setQuery("select * from sample where sampleid in tmpid");
    // model->setRelation(14, QSqlRelation("tmpid", "sampleid", "sampleid"));
    // model->select();
    ui.mytableview->setModel(model);
    // ui.mytableview->setSortingEnabled(true);
    connect(pcsy,SIGNAL(dataArrive(QList<double>)),this,SLOT(dataArrive(QList<double>)));
    connect(pcsy, SIGNAL(dataAllFinish(CMySig*)),
            this, SLOT(onDataAllFinish(CMySig*)));

    connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
            this, SLOT(updateHeader(QModelIndex, int, int)));
    connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
            this, SLOT(updateHeader(QModelIndex, int, int)));
    connect(model, SIGNAL(rowsMoved (QModelIndex,
                                     int, int,
                                     QModelIndex,
                                     int)) ,
            this,
            SLOT(rowsMoved (QModelIndex,int, int,QModelIndex,int)));
    //    connect(model, SIGNAL(currentChanged (QModelIndex,QModelIndex)),this
    //            ,SLOT(currentChanged (QModelIndex,QModelIndex)));
    //    connect(ui.tableView, SIGNAL(selectRow ( int )),
    //            this, SLOT(updateHeader(QModelIndex, int, int)));
    // d_zoomer->setTrackerMode(AlwaysOn);
    ui.qwtPlot->insertLegend(new QwtLegend(), QwtPlot::RightLegend);
    d_zoomer = new QwtPlotZoomer(ui.qwtPlot->canvas());
    //vchannel=new VStatusColor(ui.tableWidget_channel);
    //    QList<QString> l;
    //    l.append("C");
    //    l.append("S");
    //    l.append("C2");
    //    l.append("S2");
    //
    //    vchannel->setNstatus(l);
    
}
void ApplicationWindow::currentChanged (QModelIndex c,QModelIndex p)
{
}
void ApplicationWindow::updateHeader(QModelIndex i, int row, int col)
{
    qDebug()<<i<<row<<col;
}
void ApplicationWindow::on_mytableview_activated( const QModelIndex & current )
{


}
void ApplicationWindow::on_mytableview_entered( const QModelIndex & current)
{
    //    qDebug()<<"entered";
    //    int row=current.row();
    //    qDebug()<<current.data();
    //    QSqlRecord record = model->record(row);
    //    int idCol = record.indexOf("id"); // index of the field "name"
    //    long id=record.value(idCol).toInt(); // output all names
    //    sig1.loadSig(id);
    //    sig1.show(ui.qwtPlot);
    //    ui.qwtPlot->replot();
}
//void ApplicationWindow::showSig(CMySig sig1)
//{
//
//    d_zoomer = new QwtPlotZoomer( QwtPlot::xBottom, QwtPlot::yLeft,ui.qwtPlot->canvas());
//    sig1.show(ui.qwtPlot);
//        //
//}
void ApplicationWindow::on_actionImport_triggered()
{
    qDebug()<<"import";
    QString filename = QFileDialog::getOpenFileName(this,"Open txt", "", "text Files (*.txt)");
    if(!filename.isNull()){//todo
        sig1.readTextFile(filename);
        this->dataFinish();
    }
}
void ApplicationWindow::on_actionExport_triggered()
{
    qDebug()<<"export";
    if (sig1.haveData())
    {
        qDebug()<<"have data";
        QString filename = QFileDialog::getSaveFileName(this,"Save txt", "", "text Files (*.txt)");
        sig1.writeTextFile(filename);
    }
}

void ApplicationWindow::on_mytableview_clicked( const QModelIndex & current)
{
    qDebug()<<"moved";
    int row=current.row();
    QSqlRecord record = model->record(row);
    int idCol = record.indexOf("id"); // index of the field "name"
    long id=record.value(idCol).toInt(); // output all names
    sig1.detach();
    sig1.loadSig(id);
//    sig1.testData();
    ui.qwtPlot->setAxisAutoScale(QwtPlot::xBottom);
    ui.qwtPlot->setAxisAutoScale(QwtPlot::yLeft);
    sig1.show(ui.qwtPlot);
    ui.qwtPlot->replot();
    d_zoomer->setZoomBase();
}
//void ApplicationWindow::on_tableView_currentChanged( const QModelIndex & current, const QModelIndex & previous )
//{
//    qDebug()<<"current changed";
//}
void ApplicationWindow::rowsRemoved(QModelIndex i, int row, int col)
{
}
void ApplicationWindow::rowsInserted(QModelIndex i, int row, int col)
{
}

ApplicationWindow::~ApplicationWindow()
{


}
//void ApplicationWindow::buttonclickslot1()
//{
//    //ui.lineEdit->setText("hello");
//}
void ApplicationWindow::on_actionExit_triggered()
{
    this->close();
    //	Dlgabout l;
    //	l.show();
    //	l.exec();
}
void ApplicationWindow::on_actionAbout_triggered()
{
    Dlgabout *l=new Dlgabout(this);
    l->exec();

}
void ApplicationWindow::on_actionStandards_triggered()
{
        Dlgstandards l(this);
        l.exec();
//    DlgTableEdit  l(this);
//    l.setTableName("standard");
//    l.exec();
}
void ApplicationWindow::dataFinish()
{
    qDebug()<<"ApplicationWindow dataFinish";
    long sampleid=pgdb->nextSampleId();
    long id=pgdb->nextId();
    pgdb->insertTmpid(sampleid);
    qDebug()<<"sampleid"<<sampleid;

    // QSqlField fsampleid("sampleid", QVariant::Int);
    // fsampleid.setValue(QVariant((int)sampleid));
    // QSqlField fid("id", QVariant::Int);
    // fid.setValue(QVariant((int)id));
    // QSqlField fname("name", QVariant::String);
    // fname.setValue(QVariant(sig1.name));

    // QSqlField fweight("weight", QVariant::Double);
    // fweight.setValue(QVariant(sig1.weight));

    // QSqlField fmdate("mdate", QVariant::DateTime);
    QDateTime d=QDateTime::currentDateTime ();
    // fmdate.setValue(QVariant(d));

    QSqlQuery query;
    query.prepare("insert into sample(sampleid,id,name,weight,mdate)values(?,?,?,?,?)");
    query.addBindValue(QVariant((int)sampleid));
    query.addBindValue(QVariant((int)id));
    query.addBindValue(QVariant(sig1.name));
    query.addBindValue(QVariant(sig1.weight));
    query.addBindValue(QVariant(d));
    query.exec();
    model->setQuery("select * from sample where sampleid in tmpid");
    sig1.saveSig(id);
}
void ApplicationWindow::rowsMoved (const QModelIndex & sourceParent, int sourceStart
                                   , int sourceEnd
                                   , const QModelIndex & destinationParent
                                   , int destinationRow)
{
    //    qDebug()<<"moved";
    //    QSqlRecord record = model->record(destinationRow);
    //    int idCol = record.indexOf("id"); // index of the field "name"
    //    long id=record.value(idCol).toInt(); // output all names
    //    sig1.loadSig(id);
    //    sig1.show(ui.qwtPlot);
    //    ui.qwtPlot->replot();
}
void ApplicationWindow::on_actionCard_triggered()
{
    DlgCard *l=new DlgCard(this);
    l->exec();
}
void ApplicationWindow::on_pushButtonWeight_clicked()
{
    double w=ptp->read();
    QString wstr;
    wstr.setNum(w);
    ui.lineEdit_weight->setText(wstr);

}
void ApplicationWindow::on_actionBalance_triggered()
{
    DlgTp * t=new DlgTp("hello");
    t->exec();
}
void ApplicationWindow::on_actionCreateMethod_triggered()
{
    DlgMethod *l=new DlgMethod(this);
    l->exec();
}
void ApplicationWindow::on_pushButton_start_clicked()
{
    ui.pushButton_start->setEnabled(false);
    pcsy->start();
    sig1.setXn(0);
    sig1.weight=1;
    sig1.name="test";
    ui.pushButton_start->setEnabled(true);
}
void ApplicationWindow::on_pushButton_stop_clicked()
{
    ui.pushButton_stop->setEnabled(false);
    pcsy->stop();
    //dataFinish();
    ui.pushButton_stop->setEnabled(true);

}
void ApplicationWindow::dataArrive(const QList<double> &l)
{
    qDebug()<<l;
    sig1.setOneData(l,sig1.getXn());
    sig1.show(ui.qwtPlot);
    ui.qwtPlot->replot();
}
bool ApplicationWindow::isMdiAreaEnabled()
{
    return true;
}
void ApplicationWindow::enableMdiArea(bool b)
{
    ;
}
//void ApplicationWindow::on_pushButton_clicked()
//{
////    printf("clicked");
////    ScriptWindow w1(s,this);
////
////    w1.show();
//}
void ApplicationWindow::scriptsDirPathChanged(const QString&)
{
}
void ApplicationWindow::on_actionUsers_triggered()
{
    DlgTableEdit  l(this);
    l.setTableName("muser");
    l.exec();
}
void ApplicationWindow::on_actionDelete_triggered()
{
    QModelIndex  current=this->ui.mytableview->currentIndex ();
    int row=current.row();
    QSqlRecord record = model->record(row);
    int idCol = record.indexOf("id"); // index of the field "name"
    long id=record.value(idCol).toInt(); // output all names
    model->removeRow(row);
    // model->submitAll();
    pgdb->removeVoltNew(id);
}
void ApplicationWindow::on_actionOpenSample_triggered()
{
    DlgOpenSample  l(this);
    l.exec();
    //model->
   model->setQuery("select * from sample where sampleid in tmpid");
}

void ApplicationWindow::on_actionPrint_triggered()
{
    QPrinter printer(QPrinter::ScreenResolution);
    QPrintPreviewDialog dlg(&printer);
    PrintView view;
    view.setModel(model);
    connect(&dlg, SIGNAL(paintRequested(QPrinter *)),
            &view, SLOT(print(QPrinter *)));
    dlg.exec();
}
void ApplicationWindow::onDataAllFinish(CMySig *sig2)
{
    qDebug()<<"applicationWindow updateData";
    sig1.clone(sig2) ;
    this->dataFinish();
}
//void ApplicationWindow::dataArrive(const QList<double>& l)
//{
//    qDebug()<<l;
//        sig1.setOneData(l,sig1.getXn());
//        sig1.show(ui.qwtPlot);
//        ui.qwtPlot->replot();
//}
void ApplicationWindow::on_actionClear_All_triggered()
{
    qDebug()<<"clearAll";
    pgdb->clearAll();
    // model->select();
    model->setQuery("select * from sample where sampleid in tmpid");
}
void ApplicationWindow::chkLcClick(bool b){
    sig1.toggle(0,b);
    ui.qwtPlot->replot();
}

void ApplicationWindow::chkLsClick(bool b){
    sig1.toggle(1,b);
    ui.qwtPlot->replot();
}
  void ApplicationWindow::chkHcClick(bool b){
    sig1.toggle(2,b);
    ui.qwtPlot->replot();
  }
  void ApplicationWindow::chkHsClick(bool b){
    sig1.toggle(3,b);
    ui.qwtPlot->replot();
  }